package com.aipartner.config;

import com.aipartner.security.JwtAuthenticationEntryPoint;
import com.aipartner.security.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * Spring Security Configuration
 * 
 * @author AI Partner Team
 * @since 2024-01-20
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SecurityConfig {
    
    private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    
    /**
     * Password Encoder
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * Authentication Manager
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
    
    /**
     * Security Filter Chain Configuration
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
            .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
                // Public endpoints
                .antMatchers(
                        "/api/user/wechat/login",
                        "/api/user/login/wechat",
                        "/api/user/wechat-login",
                        "/user/wechat/login",
                        "/user/login/wechat"
                ).permitAll()
                .antMatchers("/api/user/register").permitAll()
                .antMatchers("/health").permitAll()
                .antMatchers("/actuator/**", "/api/actuator/**").permitAll()
                // AI生图相关接口
                .antMatchers("/api/ai-image/examples").permitAll()
                .antMatchers("/api/ai-image/system-examples").permitAll()
                .antMatchers("/api/ai-image/all-images").permitAll()
                .antMatchers("/api/ai-image/examples/*/detail").permitAll()
                .antMatchers("/illustrate-images/**").permitAll()
                // 静态资源统一放行
                .antMatchers("/uploads/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/icons/**").permitAll()
                .antMatchers("/uploads/user-examples/**").permitAll()
                .antMatchers("/uploads/generated-images/**").permitAll()
                .antMatchers("/uploads/reference-images/**").permitAll()
                // 管理员头像API端点
                .antMatchers("/api/admin/avatars/**").permitAll()
                // WebSocket endpoints
                .antMatchers("/ws/**").permitAll()
                // Swagger endpoints
                .antMatchers("/doc.html").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-ui/**").permitAll()
                // Admin login endpoint
                .antMatchers("/api/admin/login").permitAll()
                // All other endpoints require authentication
                .anyRequest().authenticated();
        
        // Add JWT filter
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
        return http.build();
    }
    
    /**
     * CORS Configuration
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}